package com.yisingle.study.map.one.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.yisingle.study.map.one.R;
import com.yisingle.study.map.one.data.CarPositionData;
import com.yisingle.study.map.one.fragment.base.BaseMapFragment;
import com.yisingle.study.map.one.map.CenterMarkerView;
import com.yisingle.study.map.one.utils.DelayTest;

import java.util.ArrayList;
import java.util.List;

/**
 * @author jikun
 *         Created by jikun on 2018/3/13.
 */

public class CenterMarkerMapFragment extends BaseMapFragment {

    private CenterMarkerView centerMarkerView;
    private DelayTest delayTest;
    private GeocodeSearch search;

    private TextView tv_start_place;

    private List<Marker> nearByCarMarkerList;

    public static CenterMarkerMapFragment newInstance() {

        Bundle args = new Bundle();

        CenterMarkerMapFragment fragment = new CenterMarkerMapFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_marker_map, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        tv_start_place = view.findViewById(R.id.tv_start_place);
        TextureMapView textureMapView = view.findViewById(R.id.textureMapView);
        delayTest = new DelayTest();
        initMapView(textureMapView, savedInstanceState);

        centerMarkerView = new CenterMarkerView(getContext());
        centerMarkerView.initInfoWindowsView(getContext(), getAMap());

        getAMap().setOnMapLoadedListener(new AMap.OnMapLoadedListener() {
            @Override
            public void onMapLoaded() {
                centerMarkerView.addCenterMarker(getAMap());
                moveCameraOnMap();
            }
        });
        getAMap().setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition cameraPosition) {
                //移除附近的车辆marker
                removeNearCarMarker();
                //停止获取附近的车辆
                delayTest.stop();
                //停止获取中心点的的道路名称
                stopFindPointNameQuery();
                //隐藏中心点marker的InfoWindow
                centerMarkerView.hideCenterMarkerInfoWindow();

            }

            @Override
            public void onCameraChangeFinish(CameraPosition cameraPosition) {

                //显示加载的infoWindow
                centerMarkerView.showLoadingInfoWindow();
                tv_start_place.setText("正在获取上车点");

                //开始获取中心点的marker坐标
                startfindPointNameQuery(new LatLonPoint(cameraPosition.target.latitude, cameraPosition.target.longitude));


            }
        });


    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        centerMarkerView.destorty();
        delayTest.destory();
    }


    /**
     * 移动地图到Marker标记点位置的方法。
     */
    private void moveCameraOnMap() {
        LatLng latLng = new LatLng(30.657505, 104.065692);
        CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 15);
        getAMap().moveCamera(cameraUpdate);
    }

    private void startfindPointNameQuery(final LatLonPoint point) {
        //创建一个GeocodeSearch  逆地理编码和地理编码类
        search = new GeocodeSearch(getContext());
        //设置监听器
        search.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
            @Override
            public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
                //逆地理编码异步返回
                //由于我们的版本是大于3.2.1 所以成功是1000
                if (i == 1000) {
                    getNearCarFakeHttp(point, regeocodeResult);

                } else {
                    centerMarkerView.showErrorInfoWindow();
                    tv_start_place.setText("获取位置失败");
                }

            }

            @Override
            public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {
                //地理编码异步返回

            }
        });
        //point - 要进行逆地理编码的地理坐标点。
        //radius - 查找范围。默认值为1000，取值范围1-3000，单位米。
        //latLonType - 输入参数坐标类型。包含GPS坐标和高德坐标。 GeocodeSearch.AMAP 、GeocodeSearch.GPS
        float radius = 1000F;
        //逆定力RegeocodeQuery构造函数
        RegeocodeQuery regeocodeQuery = new RegeocodeQuery(point, radius, GeocodeSearch.AMAP);
        //发起逆地理编码异步查询
        search.getFromLocationAsyn(regeocodeQuery);

    }


    /**
     * 获取模拟的附近的车辆的位置
     */
    private void getNearCarFakeHttp(LatLonPoint point, final RegeocodeResult regeocodeResult) {
        delayTest = new DelayTest();
        delayTest.getDelayPost(point, new DelayTest.OnCallBack() {
            @Override
            public void onSuccess(List<CarPositionData> list) {
                //RegeocodeAddress是逆地理编码搜索的地理结果。
                RegeocodeAddress regeocodeAddress = regeocodeResult.getRegeocodeAddress();
                //逆地理编码返回的格式化地址。
                String formatAddress = regeocodeAddress.getFormatAddress();
                //显示中心点marker成功的infoWindow
                centerMarkerView.showSuccessInfoWindow();
                //给定位的名称赋值到textView上
                tv_start_place.setText(formatAddress);

                //移除附近的车辆的marker
                removeNearCarMarker();
                //添加附近的车辆的marker
                addNearCarMarker(list);

            }

            @Override
            public void onFailed() {
                //显示中心点失败的infoWindow
                centerMarkerView.showErrorInfoWindow();
                tv_start_place.setText("获取位置失败");
            }
        });

    }

    private void removeNearCarMarker() {
        if (null != nearByCarMarkerList) {
            for (Marker marker : nearByCarMarkerList) {
                marker.remove();
            }
        }

    }

    private void addNearCarMarker(List<CarPositionData> list) {
        nearByCarMarkerList = new ArrayList<>();
        for (CarPositionData data : list) {
            MarkerOptions markerOptions = new MarkerOptions();
            markerOptions.icon(BitmapDescriptorFactory.fromResource(R.mipmap.car));
            markerOptions.rotateAngle(data.getBearing());
            LatLng latLng = new LatLng(data.getLatitude(), data.getLongitude());
            markerOptions.position(latLng);
            Marker marker = getAMap().addMarker(markerOptions);
            nearByCarMarkerList.add(marker);
        }
    }

    private void stopFindPointNameQuery() {
        if (null != search) {
            search.setOnGeocodeSearchListener(null);
            search = null;
        }
    }

}
